package work;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import java.util.*;

/**
 * @author Gong.Yang
 */
@Slf4j
public class MemberUtil {
    private static final String storeCode = "lrl";

    /**
     * 通过门店ID 查询门店
     */
    public static JSONObject countFindItem(String countId, String baseUrl, String token) {
        String url = baseUrl + String.format(findCounterItemGet, countId);
        HttpRequest request = HttpRequest.get(url).header("Authorization", token);
        String response = request.execute().body();
        return validJson(response);
    }

    /**
     * 创建一个门店
     */
    public static void counterCreate(Counter counter, String baseUrl, String token) {
        String url = baseUrl + createCounterItemPost;
        HttpRequest request = HttpRequest.post(url).header("Authorization", token).body(JSONUtil.toJsonStr(counter));
        String response = request.execute().body();
    }

    /**
     * 通过CustomerId换取三方卡号
     */
    public static String getThridCode(String customerId, String baseUrl, String token) {
        JSONObject customer = getCustomer(customerId, baseUrl, token);

        return Optional.ofNullable(customer)
                .map(x -> x.getJSONObject("basicInfo"))
                .map(x -> x.getStr("thirdCode"))
                .orElse(null);

    }

    /**
     * 通过CustomerId换取用户
     */
    public static JSONObject getCustomer(String customerId, String baseUrl, String token) {
        String url = baseUrl + String.format(findCustomerUrlGet, customerId);
        HttpRequest request = HttpRequest.get(url).header("Authorization", token);
        return findPageFirst(request);
    }

    /**
     * 新 通过CustomerId换取用户
     */
    public static JSONObject getCustomerByID(String customerId, String baseUrl, String token) {
        String url = baseUrl + String.format(findCustomerByIdGet, customerId);
        HttpRequest request = HttpRequest.get(url).header("Authorization", token);
        String response = request.execute().body();
        JSONObject response_json = validJson(response);
        return response_json;
    }


    /**
     * 通过三方卡号 换取用户
     */
    public static JSONObject getCustomerByThiCode(String thiCode, String baseUrl, String token) {
        String url = baseUrl + String.format(findCustomerByThiCodeGet, thiCode);
        HttpRequest request = HttpRequest.get(url).header("Authorization", token);
        return findPageFirst(request);
    }


    /**
     * 通过三方卡号 换取用户
     */
    public static JSONArray getCustomerListByThiCode(String thiCode, String baseUrl, String token) {
        String url = baseUrl + String.format(findCustomerByThiCodeGet, thiCode);
        HttpRequest request = HttpRequest.get(url).header("Authorization", token);
        String response = request.execute().body();
        JSONObject response_json = validJson(response);
        if (Objects.isNull(response_json)) {
            return null;
        }
        JSONArray content = response_json.getJSONArray("content");
        if (CollUtil.isEmpty(content)) {
            return null;
        }
        return content;
    }


    /**
     * 发卡券
     *
     * @param customerId 用户ID
     * @param templateId 卡卷模板ID
     */
    public static JSONObject couponSend(String customerId, String templateId, String baseUrl, String token) {
        String url = baseUrl + sendCouponPost;

        JSONObject body = new JSONObject();
        body.set("channelId", "sys");
        body.set("couponTemplateId", templateId);
        body.set("customerId", customerId);
        body.set("quantity", 1);
        body.set("formId", UUID.randomUUID());

        HttpRequest request = HttpRequest.post(url).header("Authorization", token).body(body.toString());
        String response = request.execute().body();
        return validJson(response);
    }

    /**
     * 卡券废弃
     *
     * @param customerId
     * @param id
     */
    public static JSONObject couponDiscard(String customerId, String id, String baseUrl, String token) {
        String url = baseUrl + disCardCouponPost;

        JSONObject body = new JSONObject();
        body.set("channelId", "sys");
        body.set("customerId", customerId);
        body.set("couponId", id);
        body.set("formId", UUID.randomUUID());

        HttpRequest request = HttpRequest.post(url).header("Authorization", token).body(body.toString());
        String response = request.execute().body();
        return validJson(response);
    }

    /**
     * 查询DL用户信息
     */
    public static JSONObject findDLCustomerInfo(String mobile, String baseUrl, String token) {
        String url = baseUrl + findDLCustomerInfo;
        String response = HttpRequest.get(url).header("Authorization", token).execute().body();
        return validJson(response);
    }

    /**
     * DL 解绑
     */
    public static void unbindByMobileOpenid(String mobile, String openId, String baseUrl, String token) {
        String url = baseUrl + String.format(unbindByMobileOpenidGet, mobile, openId);
        HttpRequest.get(url).header("Authorization", token).execute();
    }

    /**
     * 查询分页的第一个数据
     */
    private static JSONObject findPageFirst(HttpRequest request) {
        String response = request.execute().body();
        JSONObject response_json = validJson(response);
        if (Objects.isNull(response_json)) {
            return null;
        }
        JSONArray content = response_json.getJSONArray("content");
        if (CollUtil.isEmpty(content)) {
            return null;
        }
        return content.getJSONObject(0);
    }

    public static JSONArray findHAQTag(List<String> tags, String thirdCode, String baseUrl, String token) {
        JSONObject requestBody = buildHAQTagBody(tags, thirdCode);
        return findHAQTag(requestBody, baseUrl, token);
    }

    public static JSONArray findHAQTag(JSONObject requestBody, String baseUrl, String token) {
        HttpRequest request = HttpRequest.post(baseUrl + findHAQTagUrlPost)
                .body(requestBody.toString())
                .header("Authorization", token);
        String body = request.execute().body();
        JSONObject response = validJson(body);
        return Optional.ofNullable(response)
                .map(x -> x.getJSONArray("tags"))
                .orElse(null);
    }

    public static JSONObject buildHAQTagBody(List<String> tags, String thirdCode) {
        JSONObject body = new JSONObject();
        body.set("userIdType", "member_code");
        body.set("userId", thirdCode);
        body.set("tags", tags);
        return body;
    }


    private static JSONObject validJson(String response) {
        if (!JSONUtil.isTypeJSON(response)) {
            log.info("【响应非json】-》{}", response);
            return null;
        }
        return JSONUtil.parseObj(response);
    }


    //通过customerId查询用户
    public static final String findCustomerUrlGet = "/member-manage/store/" + storeCode + "/customer_info_data?page=0&size=10&expression=id+eq+%s";

    //新 通过customerID 查询用户
    public static final String findCustomerByIdGet = "/member-manage/store/" + storeCode + "/customer_info_data/%s";

    //通过三方卡号查询用户
    public static final String findCustomerByThiCodeGet = "/member-manage/store/" + storeCode + "/customer_info_data?page=0&size=10&expression=basicInfo.thirdCode+eq+%s";

    //根据三方卡号查询tag信息
    public static final String findHAQTagUrlPost = "/member-manage/manage/" + storeCode + "/haq/batchTags";

    //根据ID 查询门店
    public static final String findCounterItemGet = "/member-manage/store/" + storeCode + "/counter/item/%s";

    //创建 门店
    public static final String createCounterItemPost = "/member-manage/store/" + storeCode + "/counter";

    // 发送卡券
    public static final String sendCouponPost = "/member-manage/" + storeCode + "/coupon_transaction/create";
    //废弃卡券
    public static final String disCardCouponPost = "/member-manage/" + storeCode + "/coupon_transaction/discard";

    //DL 通过手机号获取用户DL信息
    public static final String findDLCustomerInfo = "/member-manage/" + storeCode + "/data_lake/customer/find/info/mobile/";//+手机号

    //DL 通过手机号和openid解绑用户
    public static final String unbindByMobileOpenidGet = "/member-manage/" + storeCode + "/data_lake/customer/unbind_by_mobile_openid/%s/%s";//{mobile}/{openId}

    //门店实体类
    @Data
    static public class Counter {

        //@ApiModelProperty(value = "柜台id", example = "与柜台编号一致")
        private String id;

        //@ApiModelProperty(value = "柜台编号")
        private String code;

        //@ApiModelProperty(value = "柜台名称")
        private String name;

        //@ApiModelProperty(value = "柜台marsCode")
        private String marsCode;

        //@ApiModelProperty(value = "门店类型")
        private String type;


        //@ApiModelProperty(value = "业务类型")
        private List<String> bizType;

        //@ApiModelProperty(value = "电话")
        private String phone;

        //@ApiModelProperty(value = "门店座机")
        private String telPhone;

        //@ApiModelProperty(value = "维度")
        private double latitude;

        //@ApiModelProperty(value = "经度")
        private double longitude;

        //@ApiModelProperty(value = "省份")
        private String province;

        //@ApiModelProperty(value = "城市")
        private String city;

        //@ApiModelProperty(value = "区域")
        private String region;

        //@ApiModelProperty(value = "地址")
        private String address;


        //@ApiModelProperty(value = "是否启用")
        private boolean active;

        //@ApiModelProperty(value = "是否默认")
        private boolean defaultFlag;

        //@ApiModelProperty(value = "柜台状态", example = "营业中:onBusiness,即将开业:waitStartBusiness,歇业状态:endBusiness")
        private String counterStatus;


        //@ApiModelProperty(value = "即将开业时间")
        private Date startBusinessTime;

        //@ApiModelProperty(value = "歇业时间")
        private Date endBusinessTime;

        //@ApiModelProperty(value = "父节点id")
        private String parentId;

        //@ApiModelProperty(value = "排序值")
        private Integer order;

        //@ApiModelProperty(value = "企业微信id")
        private Integer qyChatId;

        //@ApiModelProperty(value = "门店店长id")
        private List<String> departmentLeader;

        //@ApiModelProperty(value = "创建时间")
        private Date createTime;

        //@ApiModelProperty(value = "更新时间")
        private Date updateTime;

    }
}
